﻿/*
Copyright © Naveen Hegde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Neither the name of the author, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written 
permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace NvinInstaller
{
    public partial class ApplicationDirectoryControl : UserControl
    {
        public ApplicationDirectoryControl()
        {
            InitializeComponent();
        }

        private void treeViewApplicationDir_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            treeViewApplicationDir.SelectedNode = e.Node;
            e.Node.ContextMenuStrip = contextMenuStrip;

            //treeViewApplicationDir.SelectedImageIndex = e.Node.ImageIndex;
            ApplicationDirectoryNode node = (ApplicationDirectoryNode)e.Node;

            if (((ApplicationDirectoryNode)e.Node).Type == ApplicationDirNodeType.File)
            {
                for (int i = 0; i < contextMenuStrip.Items.Count; i++)
                {
                    switch (contextMenuStrip.Items[i].Text)
                    {
                        case "Add Folder":
                            contextMenuStrip.Items[i].Enabled = false;
                            break;
                        case "Delete Folder":
                            contextMenuStrip.Items[i].Enabled = false;
                            break;
                        case "Add File":
                            contextMenuStrip.Items[i].Enabled = false;
                            break;
                        case "Delete File":
                            contextMenuStrip.Items[i].Enabled = true;
                            break;
                        case "Exand":
                            contextMenuStrip.Items[i].Enabled = false;
                            break;
                        case "Collapse":
                            contextMenuStrip.Items[i].Enabled = false;
                            break;

                    }
                }
            }
            else
            {
                for (int i = 0; i < contextMenuStrip.Items.Count; i++)
                {
                    if (contextMenuStrip.Items[i].Text.Equals("Delete File"))
                    {
                        contextMenuStrip.Items[i].Enabled = false;
                    }
                    else
                    {
                        contextMenuStrip.Items[i].Enabled = true;
                    }
                }
            }
        }

        private void treeViewApplicationDir_AfterSelect(object sender, TreeViewEventArgs e)
        {
            ApplicationDirectoryNode node = (ApplicationDirectoryNode)e.Node;
            if (node.Type == ApplicationDirNodeType.File)
            {
                propertyGrid.SelectedObject = (Component)node.Content;
                treeViewApplicationDir.SelectedImageIndex = 1;
            }
            else
            {
                propertyGrid.SelectedObject = null;
                treeViewApplicationDir.SelectedImageIndex = 0;
            }
            e.Node.Expand();
        }

        private void addFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddFolderNode("New Folder");
        }

        private void deleteFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteNode();
        }

        private void addFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddFileNode();
        }

        private void deleteFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteNode();
        }

        private void exandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeViewApplicationDir.SelectedNode.Expand();
        }

        private void collapseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            treeViewApplicationDir.SelectedNode.Collapse();
        }

        private void skinButtonAddFolder_Click(object sender, EventArgs e)
        {
            string name = GetFolderName();
            AddFolderNode(name);
        }

        private string GetFolderName()
        {
            TreeNode node = treeViewApplicationDir.SelectedNode;
            if(node == null)
            {
                return "New Folder0";
            }
            return "New Folder" + node.Nodes.Count;
        }

        private void AddFolderNode(string text)
        {            
            ApplicationDirectoryNode node = new ApplicationDirectoryNode(ApplicationDirNodeType.Directory,text);
            if (treeViewApplicationDir.SelectedNode != null && ((ApplicationDirectoryNode)treeViewApplicationDir.SelectedNode).Type == ApplicationDirNodeType.Directory)
            {
                treeViewApplicationDir.Select();
                treeViewApplicationDir.SelectedImageIndex = 0;
                treeViewApplicationDir.SelectedNode.Nodes.Add(node);
                treeViewApplicationDir.SelectedNode = node;
                node.BeginEdit();
            }
            else
            {
                //treeViewApplicationDir.Select();
                //treeViewApplicationDir.SelectedImageIndex = 0;
                treeViewApplicationDir.Nodes.Add(node);
                treeViewApplicationDir.SelectedNode = node;
                node.BeginEdit();
            }            
        }

        private void skinButtonAddFile_Click(object sender, EventArgs e)
        {
            AddFileNode();
        }

        private void AddFileNode()
        {
            if (treeViewApplicationDir.SelectedNode == null)
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Multiselect = true;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    foreach (string path in dlg.FileNames)
                    {
                        if (FileExist(path))
                        {
                            MessageBox.Show("File already added to the selected folder", "Add file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        ApplicationDirectoryNode node = new ApplicationDirectoryNode(ApplicationDirNodeType.File, path);
                        treeViewApplicationDir.SelectedImageIndex = 1;
                        treeViewApplicationDir.Nodes.Add(node);
                        node.ImageIndex = 1;
                        treeViewApplicationDir.Select();                        
                    }
                }
            }
            if (((ApplicationDirectoryNode)treeViewApplicationDir.SelectedNode).Type == ApplicationDirNodeType.Directory)
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Multiselect = true;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    foreach (string path in dlg.FileNames)
                    {
                        if (FileExist(path))
                        {
                            MessageBox.Show("File already added to the selected folder", "Add file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        ApplicationDirectoryNode node = new ApplicationDirectoryNode(ApplicationDirNodeType.File, path);
                        if (treeViewApplicationDir.SelectedNode != null && ((ApplicationDirectoryNode)treeViewApplicationDir.SelectedNode).Type == ApplicationDirNodeType.Directory)
                        {
                            treeViewApplicationDir.SelectedNode.Nodes.Add(node);
                            node.ImageIndex = 1;
                            treeViewApplicationDir.Select();
                            treeViewApplicationDir.SelectedNode.Expand();
                        }
                        else
                        {
                            treeViewApplicationDir.SelectedImageIndex = 1;
                            treeViewApplicationDir.Nodes.Add(node);
                            node.ImageIndex = 1;
                            treeViewApplicationDir.Select();
                        }
                    }
                }
            }
        }

        private bool FileExist(string path)
        {
            try
            {
                TreeNode selectedNode = treeViewApplicationDir.SelectedNode;
                FileInfo fileInfo = new FileInfo(path);
                string name = fileInfo.Name;
                foreach (TreeNode node in selectedNode.Nodes)
                {
                    if (node.Text.Equals(name, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            catch
            {
            }
            return false;
        }

        private void skinButtonDelete_Click(object sender, EventArgs e)
        {
            DeleteNode();
        }

        private void DeleteNode()
        {
            if (treeViewApplicationDir.SelectedNode != null)
            {
                if (treeViewApplicationDir.SelectedNode.Nodes.Count > 0)
                {
                    if (MessageBox.Show("Are you sure you want to delete this Directory and child nodes ?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    {
                        treeViewApplicationDir.SelectedNode.Remove();
                    }
                }
                else
                {                    
                    treeViewApplicationDir.SelectedNode.Remove();                    
                }
            }
        }

        public void Reload()
        {
            if (ApplicationManager.GetApplicationManager().ApplicationTree != null)
            {                
                panelApplicationDir.Controls.Remove(treeViewApplicationDir);
                treeViewApplicationDir = ApplicationManager.GetApplicationManager().ApplicationTree;
                treeViewApplicationDir.Dock = DockStyle.Fill;
                treeViewApplicationDir.ImageList = imageList;
                treeViewApplicationDir.LabelEdit = true;
                this.treeViewApplicationDir.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.treeViewApplicationDir_AfterLabelEdit);
                this.treeViewApplicationDir.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewApplicationDir_AfterSelect);
                this.treeViewApplicationDir.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeViewApplicationDir_MouseDown);
                this.treeViewApplicationDir.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeViewApplicationDir_NodeMouseClick);
                SetNodeImages();
                panelApplicationDir.Controls.Add(treeViewApplicationDir);
            }
        }

        private void SetNodeImages()
        {
            foreach (TreeNode node in treeViewApplicationDir.Nodes)
            {
                if (((ApplicationDirectoryNode)node).Type == ApplicationDirNodeType.Directory)
                {
                    node.ImageIndex = 0;
                }
                else
                {
                    node.ImageIndex = 1;
                }
            }
        }

        public void UnLoad()
        {
            if (ApplicationManager.GetApplicationManager().ApplicationTree == null)
            {
                ApplicationManager.GetApplicationManager().ApplicationTree = treeViewApplicationDir;
            }
        }

        private void treeViewApplicationDir_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (((ApplicationDirectoryNode)e.Node).Type == ApplicationDirNodeType.File)
            {
                e.CancelEdit = true;
            }
            else if (((ApplicationDirectoryNode)e.Node).Type == ApplicationDirNodeType.Directory)
            {
                if(FolderExists(e.Node,e.Label))
                {
                    e.CancelEdit = true;
                }
            }
        }

        private bool FolderExists(TreeNode treeNode, string p)
        {
            if (treeNode.Parent == null)
            {
                foreach(TreeNode rootNodes in treeViewApplicationDir.Nodes)
                {
                    if (rootNodes != treeNode && rootNodes.Text.Equals(p, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            else
            {
                TreeNode parent = treeNode.Parent;
                foreach (TreeNode node in parent.Nodes)
                {
                    if (node != treeNode && node.Text.Equals(p, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private void treeViewApplicationDir_MouseDown(object sender, MouseEventArgs e)
        {
            treeViewApplicationDir.SelectedNode = null;
        }

        private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = treeViewApplicationDir.SelectedNode;
            if (((ApplicationDirectoryNode)node).Type == ApplicationDirNodeType.Directory)
            {
                node.BeginEdit();
            }
        }

        private void applyFeatureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ApplyFeature applyFeature = new ApplyFeature();
            if (applyFeature.ShowDialog() == DialogResult.OK)
            {
                TreeNode node = treeViewApplicationDir.SelectedNode;
                foreach (TreeNode childNode in node.Nodes)
                {
                    ApplicationDirectoryNode appNode = (ApplicationDirectoryNode)childNode;
                    switch(appNode.Type)
                    {
                        case ApplicationDirNodeType.File:
                            Component cmp = (Component)appNode.Content;
                            cmp.Feature = applyFeature.SelectedFeature.Name;
                            break;
                        case ApplicationDirNodeType.Directory:
                            ApplyFeatures(appNode,applyFeature.SelectedFeature);
                            break;
                    }
                }
            }
        }

        private void ApplyFeatures(ApplicationDirectoryNode appNode, Feature feature)
        {
            foreach (TreeNode childNode in appNode.Nodes)
            {
                ApplicationDirectoryNode node = (ApplicationDirectoryNode)childNode;
                switch (node.Type)
                {
                    case ApplicationDirNodeType.File:
                        Component cmp = (Component)node.Content;
                        cmp.Feature = feature.Name;
                        break;
                    case ApplicationDirNodeType.Directory:
                        ApplyFeatures(node, feature);
                        break;
                }
            }
        }
    }
}
